package com.xdemo.msg;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Queue;

import org.jboss.netty.handler.codec.http.HttpChunk;

public class NettyChunkInputStream extends InputStream {

	private Queue<HttpChunk> chunkQueue = new LinkedList<HttpChunk>();

	private HttpChunk currentChunk = null;

	public boolean putChunk(HttpChunk chunk) throws IOException {
		chunkQueue.add(chunk);
		return true;
	}

	@Override
	public int read() throws IOException {
		if(currentChunk == null) {
			nextChunk();
		}
		if(currentChunk == null) {
			return -1;
		}
		if(!currentChunk.getContent().readable()) {
			nextChunk();
			if(currentChunk == null) {
				return -1;
			}
		}
		if(!currentChunk.getContent().readable()) {
			return -1; 
		}
		byte _resultByte = currentChunk.getContent().readByte();
		return _resultByte >= 0 ? _resultByte : 256 + _resultByte;
	}
	
	private void nextChunk() {
		currentChunk = chunkQueue.poll();
	}

}